package com.lm.itextpdf.example;

import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;

public class AddWatermarkExample {
    public static void main(String[] args) throws Exception {
        String src = "input.pdf";
        String dest = "watermarked.pdf";

        PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
        PdfFont font = PdfFontFactory.createFont();
        int n = pdfDoc.getNumberOfPages();
        for (int i = 1; i <= n; i++) {
            PdfCanvas canvas = new PdfCanvas(pdfDoc.getPage(i));
            Rectangle pageSize = pdfDoc.getPage(i).getPageSize();

            canvas.saveState();
            // 设置水印透明度
            canvas.setFillColorRgb(0.75f, 0.75f, 0.75f); // 设置颜色为灰色
            canvas.beginText()
                    .setFontAndSize(font, 60)
                    .moveText(pageSize.getWidth() / 2 - 150, pageSize.getHeight() / 2)
                    .showText("CONFIDENTIAL") // 水印文字内容
                    .endText();
            canvas.restoreState();
        }

        pdfDoc.close();
        System.out.println("Watermarked PDF created at: " + dest);
    }
}
